/**
 * Copyright (c) 2006-2012 Las Venturas Playground, LVP Mineground
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package mineground.bukkit;

import org.bukkit.plugin.java.JavaPlugin;
import mineground.core.Mineground;

/**
 * The Bukkit Plugin is the entry point of the Las Venturas Mineground game when run as a Bukkit
 * plugin. Considering it's not unthinkable that Bukkit will be replaced with a Plugin API created
 * by Minecraft itself, this layer should be kept as thin as possible, allowing us to easily
 * transition to any new plugin model.
 */
public class Plugin extends JavaPlugin {
    /**
     * The actual Las Venturas Mineground runtime contains the actual code and logic used to
     * provide a unique experience to our players. Communicate to it.
     */
    private Mineground mMinegroundRuntime;

    /**
     * The onEnable() method will be called by Bukkit when the plugin is being enabled. Do not use
     * the onLoaded() method as the intent of reloading is to restart the mode altogether. In here
     * we initialize the Mineground instance, and schedule a repeating task on Bukkit's main
     * thread which should run once per server tick (in general, ~50 milliseconds).
     * 
     * When the server is busy, the frequency may subject to delays. Don't do any intensive
     * processing in here, as it will by executed on the server thread and is thus able to
     * completely block any other processing by the server.
     */
    public void onEnable() {
        mMinegroundRuntime = new Mineground();
        getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
            public void run() {
                mMinegroundRuntime.onTick();
            }
        }, 20L, 1L);
        
        NativePlayer.setMessageLoop(mMinegroundRuntime.getMessageLoop());
        EventListener.create(this, mMinegroundRuntime.getMessageLoop());
    }
    
    /**
     * Similarly, listen to commands from the Bukkit server about disabling the plugin, after which
     * we have to shut down our entire runtime, threading and connections. Also remove all the
     * tasks created by this Plugin, as we want to clean up our mess.
     */
    public void onDisable() {
        getServer().getScheduler().cancelTasks(this);
        mMinegroundRuntime.onShutdown();
    }
}
